"""
@author: Sergiy Tsymbalyuk
"""

from repoze.what.predicates import Predicate, in_group

from hrms.lib.base import Session
from hrms.model.person import Employee
from chowa.model.organization import Division

class from_district(Predicate):
    message = u'User must be from same district with employee'
    
    def evaluate(self, environ, credentials):
        routes_dict = environ.get('pylons.routes_dict')
        district_id = routes_dict.get('id')
        try:
            identity = environ.get('repoze.who.identity')
            user = identity['user']
            employee = Session.query(Employee).get(user.person_id)
            if employee.division.district_id == int(district_id):
                return
        except:
            self.unmet()
        self.unmet()

class profile(Predicate):
    message = u'User must be from same district with employee'
    
    def evaluate(self, environ, credentials):
        if in_group('hrms.administrators').is_met(environ):
            return
        user_employee = None
        identity = environ.get('repoze.who.identity')
        if identity:
            user = identity['user']
            user_employee = Session.query(Employee).get(user.person_id)
        else:
            self.unmet()

        routes_dict = environ.get('pylons.routes_dict')
        relation = routes_dict.get('relation')
        district = None
        if relation == 'employee':
            employee_id = routes_dict.get('id')
            employee = Session.query(Employee).get(employee_id)
            try:
                district = employee.division.district
            except:
                self.unmet()
        elif relation == 'division':
            division_id = routes_dict.get('id')
            division = Session.query(Division).get(division_id)
            try:
                district = division.district
            except:
                unmet()
        else:
            self.unmet()
        try:
            user_district = user_employee.division.district
            if district and \
               (user_district == district) and \
               in_group('hrms.hr').is_met(environ):
                return
            else:
                self.unmet()
        except:
            self.unmet()
        self.unmet()
